package org.exaple.laixe;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.TextView;

public class Hoc extends Activity{
	private Button btn_Next;
	private Button btn_Back;
	private WebView webView;
	private CheckBox chkCorrect;
	//private Button btn_Question;
	private boolean showAnswer;
	private String currentQuestion;
	private Button btn_Go;
	private EditText edt_Question;
	private TextView text_Question;
	private int scale; 	// store scale for webview  in next questions
	
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.hoc);
        
        // Find controls on the screen main.xml
        btn_Back = (Button) findViewById(R.id.learn_btn_Back);
        btn_Next = (Button) findViewById(R.id.learn_btn_Next);
        webView = (WebView) findViewById(R.id.webView);
        chkCorrect = (CheckBox) findViewById(R.id.chk_Correct);
        //btn_Question = (Button) findViewById(R.id.btn_Question);
        btn_Go = (Button) findViewById(R.id.btn_Go);
        edt_Question = (EditText) findViewById(R.id.edt_Question);
        text_Question = (TextView) findViewById(R.id.text_Question);        
        
        // Set zoom control       
        webView.getSettings().setSupportZoom(true);//Zoom Control on web (You don't need this 
        											//if ROM supports Multi-Touch
        webView.getSettings().setBuiltInZoomControls(true); //Enable Multitouch if supported by ROM
        webView.getSettings().setUseWideViewPort(true);  
        // Turn on javascript 
        webView.getSettings().setJavaScriptEnabled(true);      
        
        
        btn_Next.setOnClickListener( new View.OnClickListener() {
			
			public void onClick(View v) {
				ProcessQuestionString(1);
				ShowQuestion( currentQuestion );
				System.out.println(currentQuestion);
			}
		});
        
        btn_Back.setOnClickListener( new View.OnClickListener() {
			
			public void onClick(View v) {
				ProcessQuestionString(-1);
				ShowQuestion( currentQuestion );
				System.out.println(currentQuestion);
			}
		});
        
        chkCorrect.setOnClickListener( new View.OnClickListener() {
			
			public void onClick(View v) {
				if( ((CheckBox)v).isChecked() ) {
					showAnswer = true;
				}
				else {
					showAnswer = false;
				}
				// Show Question with answer again
				ShowQuestion( currentQuestion );
			}
		});
        
        btn_Go.setOnClickListener( new View.OnClickListener() {
			
			public void onClick(View v) {
				if( Integer.parseInt(edt_Question.getText().toString()) >= 1 
						&& Integer.parseInt(edt_Question.getText().toString()) <= 405 )
				{
					currentQuestion = edt_Question.getText().toString();
					ProcessQuestionString(0);
					ShowQuestion( currentQuestion );
				}
				
			}
		});
        
        if(savedInstanceState != null) {
        	// onRestoreIntanseState
        }
        else {
        	currentQuestion = "001".toString();
        	showAnswer = false;
        	edt_Question.setText(currentQuestion);
        	ShowQuestion( currentQuestion );
        }
        
	}
	
	// Create Option Menu
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.learn_menu, menu);
	    return true;
	}
	
	// Process When user click on Option emnu
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.learn_menuThietLap:
			startActivity(new Intent(this, Prefs.class));
			return true;
		case R.id.learn_menuLuat:
			startActivity(new Intent(this, Hoc_help.class));
			return true;
		case R.id.learn_menuThoat:
			onExit();
			return true;

		default:
			return super.onOptionsItemSelected(item);
		}
	}
	
	@Override
	public void onSaveInstanceState(Bundle savedInstanceState) {
		savedInstanceState.putString( "currentQuestion", currentQuestion);
		savedInstanceState.putBoolean("answer", showAnswer);		
	}
	
	@Override 
	public void onRestoreInstanceState(Bundle state) {
		currentQuestion = state.getString("currentQuestion");
		showAnswer = state.getBoolean("answer");
		//
		ShowQuestion(currentQuestion);
		edt_Question.setText(currentQuestion);
		chkCorrect.setChecked(showAnswer);
		super.onRestoreInstanceState(state);
	}
	
	@Override
	public void onResume() {
		super.onResume();
		Music.play(this, "file:///sdcard/data/org.exaple.laixe/2000.mp3");
	}
	
	@Override
	public void onPause() {
		super.onPause();
		Music.stop(this);
	}
	
	
		
	// Event Back button when users press
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)  {
	    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {System.out.println(currentQuestion);
	        if(Integer.parseInt(currentQuestion) == 1 ) {
	        	// asking user to exit if they are viewing the first question
	        	//System.out.println(currentQuestion);
	        	onExit();
	        } else {
	        	previous();
	        }
	        return true;
	    }
	    return super.onKeyDown(keyCode, event);
	}
	
	private void onExit() {		
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Chọn Đồng ý để thóat, hoặc chọn Tiếp tục học để học tiếp.")
		       .setCancelable(false)
		       .setTitle("Bạn muốn thoát?")
		       .setPositiveButton("Đồng ý", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                finish();
		           }
		       })
		       .setNegativeButton("Tiếp tục học", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                dialog.cancel();
		           }
		       })
		       .setIcon(R.drawable.ic_dialog_info);
		AlertDialog alert = builder.create();		
		alert.show();
	}

	private void previous() {
		ProcessQuestionString(-1);
		ShowQuestion( currentQuestion );		
	}

	public void ProcessQuestionString(int add) {
		int currentQues = Integer.parseInt(currentQuestion);
		currentQues +=add;
		String current = "";
		if( currentQues <= 0 )
			currentQues = 1;
		if( currentQues >= 405)
			currentQues = 405;
		
		if( currentQues >= 1 && currentQues <= 9)
			current = "0" + "0" + String.valueOf( currentQues );
		else if( currentQues >=10 && currentQues <=99 )
			current  = "0" + String.valueOf( currentQues );
		else 
			current = String.valueOf( currentQues );
		
		currentQuestion = current;
	}
	
	// Show Questions
	public void ShowQuestion(String number) {
    	String baseUrl = "file:///sdcard/data/org.exaple.laixe/";
    	String data = getStringFromURL( number + ".html");
    	text_Question.setText( number );
    	// Display current question
    	scale = (int)(100 * webView.getScale()); // keep the last zoom ratio
    	webView.loadDataWithBaseURL(baseUrl, data, "text/html", "utf-8", "");
    	webView.setInitialScale(scale);
    	System.out.println(currentQuestion);
    }
    
    // Read File from Assets and return to a string to process later
    public String getStringFromURL(String s) {
    	String str = "";
    	try {
	    	InputStream is = getApplicationContext().getAssets().open(s);
	    	InputStreamReader input = new InputStreamReader(is);
	    	int charRead;	    	
	    	char[] bufer = new char[2000];
	    	while( (charRead = input.read(bufer)) > 0 ) {
	    		String readString = String.copyValueOf(bufer, 0, charRead);
	    		str += readString;
	    		bufer = new char[2000];
	    	}
	    	is.close();
    	}
    	catch(IOException io) {
    		io.printStackTrace();
    	}
    	// Process str when displaying anwser
    	if(showAnswer == true) {
    		// Đổi style:"display= none" -> true
    	    str = str.replaceAll( "display: none", "display: true");    	
    	}
    	return str;
    }
}
